<?php 
namespace xfyzf\plugins\appjk\controller;
use xfyzf\api\controller\Examine;
use lib\Commontc;
use lib\PluginScanner;
use auth;
class Index{
public $priKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDFKaddMnBv3LAh
dCg+ZtuM/yv9EZyN8LfkvzO91oEJbc65CqHtPYvIKFCdMHKu1Iv+W67+5DT/GWGq
JvewTQyj/8AG1WgATVU6OEGk4Zre1QMJLbgNlMeNWjz8PC+cpgxwwk8nmIiDs2kR
npkHAdQ8yoDr4h/SOips8cftopt9dgfyGkhj1b9Gx98P9qZTDJ+l2T/hIFkGGs6O
LC7Nh4RAsmJ4DxjDoQMcple7sSbqRCGKnw3HYI+zRJx8vfkhcmMFH88aYI3xTSrS
gCJgrT+mqKtma8xpFFPRsLxzEx4USquz+itOOlruMKmf0pKenbWZO/ZL5QVRzxLM
0dEye0c5AgMBAAECggEAUYsNtkTjLdCnY96nuk9OJH1w0wTSq/3QAKJ3ot8xlRW+
NtfH6tfWlRzfYnOkKtyrXbLLqI33wT3dH8NoE5l6TeW7pNfkYKObSS31MF1CcUDG
NaicA7nx4mtc57F4u6ANayFiHW0/oMC2BtyCS9ycy9uxAF4QbSEzZMWGu6jSCEvr
GsnpkAlwWNj7Ib0GoonswK0WKq4TDx2zskDfExI38wYjqNZAgjCJi/hYZChCSs86
ygkd3VpqqD46BGLW7FKwt5BZrSeBaqIMnPOJJm5i4jPR0CV4GP3e1SbL97MuTWdF
jVFLEmr7Bc4cBiztAwhcLPBRSSc7flSbsW4QkXi7dQKBgQD16KiJXZ4D5rGlTkLR
NM0OOlofqLI2ZTPvuD8dJxMCCwLlO+IwRNZwFYx+7a86fFCBm9W1JFJtm7hNJEAs
2PBzYrJlGc5NYQQhjqhPXcosNChY/y3HuZuTQvYypZ0nSZ0MsKurVrWAAe2iu1Hj
EBV8AuWnjvhutkzdnDBO/tQ8FwKBgQDNQOdbvdVGtgftK/uXFtHHjTJtMBtrrCSy
k/Vi/SyO7fOnq6mABdAjyFxJjSnER3pu9/ol8UiO7VTFuGxQFU1Au/JMqX0s8g/6
ZiKziEBUmd6qVZGGyFSgrmjs0RE57c6oyF0IGzNj2HILZSGYH+457xNLgOEFlmEQ
3+Fr10oZLwKBgCZY/c9OFhItq45Hwgu13DRXzS4atI/fAFZluRHmwgQTi4QL7p3w
XjBka+BvWGAaesN7dbwlyeTl37vH52oW+ohD3+X8PDu84VQKVxzpV1nFWHVodc8r
lqNEUfhb80HpLOCJvHufrfYkVtaFt6NdIryQBxg2J2+8Zgg5Dx+Chb5JAoGBAInd
colYtQzN7/0Kce9GUJns6VYV3hUwh2W7pDNdQrSud97DmxJ21Rtz1SlCPC+uozou
LkOWEdqO50X3XilcZYt5soJzxbSO0tSqDdzxQ+SPhdR7rUgO/2j+PVP0CdITPaB5
FKQBQT9rfw7QWwRHTkhzoU4xvvN10rT26/73mLnZAoGBANHpiwlGbSFUa8tQN8V8
HOafzEsQXidOMcPtAa95e334mAwAqG1Jlv/ofRdBrnYQwOPwt30ML4QJSHNd93Lm
Qa44Xg3n1cMaRIUcYu6w3FM+7lIH2i2MLjiSaed10KXuQxoYdLNiaDM/VJttlH6m
5cHMwRPI+EgOhh+ScIRsC/2w';
    public $info = [
        "name"        =>'appjk',//支付插件英文名称，需和目录名称一致，不能有重复
        "showname"    =>'APP挂机',//支付插件显示名称
        "author"      =>'afei66', //支付插件作者
        'auth'        =>false,//授权开关
		'pwd'         =>'xfappgua1745387748####****',//明文 密码
		'path'        =>'appjkauth.ini',//授权效验文件  注意 必须唯一 结尾.ini
        ];
        
    public function appcron(){//App监控
        $data = input("post")?:input("input");
        $key  = $data['token'];
        if(!$key)exitjson(-1,'key不可为空');
        $authtoken = $this->tokenkeyverify($key);
        if(!$authtoken)exitjson(-1,'token信息错误！');
        $pid = $authtoken['pid'];
        $userrow = $this->userrow($pid);
        if(!$userrow)exitjson(-1,'用户不存在');
        $timess=time()+mt_rand(5, 10);
        $sql = "SELECT * FROM pay_qrlist WHERE pid=:pid and `hook_type`= :hook_type ";
        $paramsSelect = [
            'pid' => $pid,
            'hook_type'=>3
        ];
        $rs = safeSqlQuery($sql, $paramsSelect);
        $timess=time()+  15;
        $cookie = md5($timess);
        if($rs['count']>0){
            foreach ($rs['result'] as $res){
               $sql = "update `pay_qrlist` set `crontime`='{$timess}' ,`status`='1' , `cookie`='{$cookie}' WHERE `id`='{$res['id']}'";
               executeSQLQuery($sql,'update');
            }
            
        }
        exitjson(200,'Cron OK');
    }
    public function appnotify(){
        $data = input("post")?:input("input");
        $money = $data['money'];
        $key   = $data['token'];
        $type  = $data['type'];
        if(empty($money) || empty($key) || empty($type))exitjson(-1,'所有参数不可为空！');
        $authtoken = $this->tokenkeyverify($key);
        if(!$authtoken)exitjson(-1,'token信息错误！');
        $pid = $authtoken['pid'];
        $userrow = $this->userrow($pid);
        if(!$userrow)exitjson(-1,'用户不存在');
        $time      = time();
        $sql = "SELECT * FROM pay_order WHERE status=:status  and  price=:money and outtime>:time and pid = :pid and type=:type limit 1";
        $paramsSelect = [
            'pid' => $pid,
            'type'=> $type,
            'money' => $money,
            'time'=>$time,
            'status'=>0
        ];
        $srow = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        $typename = array(
            'wxpay'=>'微信APP挂机',
            'qqpay'=>'QQAPP挂机',
            'alipay'=>'支付宝APP挂机'
            );
        if($srow){
            if($srow['status'] == '0'){
                $E_type = $typename[$type];
                $url=creat_callback($srow);
                $data=get_curl($url['notify']);
                xfhtemail($pid,$money,$E_type,$srow['name'],$srow['trade_no']); 
                createLog($pid,'自动回调订单('.$E_type.')：'.$srow['trade_no'],http_ip());
                $arr = array(
                    'trade_no'=>$srow['trade_no'],
                    'money'=>$money,
                    'qr_id'=>$res['id']
                );
                exitjson(200,'success',$arr);
            }
        }else{
            exitjson(-1,'无匹配金额');
        }
    }
    public function APP_Qrlist(){
        global $islogin_user,$userrow,$user_pid,$conf,$httphost;
        $title= 'APP挂机码子管理';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        $get = input("get");
        $my  = $get['my']??'list';
        $id  = $get['id']??'';
        $types = ['alipay', 'wxpay', 'qqpay'];
         $cookie_ok_counts = [];
         $cookie_no_counts = [];
        
        foreach ($types as $type) {
            $sql_cookie_ok = "SELECT COUNT(*) AS count FROM pay_qrlist WHERE status = '1' AND hook_type ='3' AND type = '{$type}' AND `pid` = '{$user_pid}'";
            $cookie_ok_counts[$type] = executeSQLQuery($sql_cookie_ok)['count'];
        
            $sql_cookie_no = "SELECT COUNT(*) AS count FROM pay_qrlist WHERE status != '1' AND hook_type ='3' AND type = '{$type}' AND `pid` = '{$user_pid}'";
            $cookie_no_counts[$type] = executeSQLQuery($sql_cookie_no)['count'];
        }
        $sql  = "SELECT COUNT(*) AS count from pay_qrlist WHERE `pid`='{$user_pid}' and hook_type ='3' ";
        $numrows = executeSQLQuery($sql)['count'];
        $con='共有 <b>'.$numrows.'</b> 条记录';
        $sql  = "SELECT COUNT(*) AS count from pay_qrlist WHERE `pid`='{$user_pid}'";
        $numrow = executeSQLQuery($sql)['count'];
        $pagesize=5;
         $pages=0;
         if(isset($numrows)){
                $pages=intval($numrows/$pagesize)+1;
         }
         if(isset($get['page'])){
             $page=intval($get['page']);
         }else{
             $page=1;
         }
         $offset = $pagesize * ($page - 1);
         $conditions[] = "`pid` = :pid";
         $params['pid'] = $user_pid;
         $whereClause = implode(' AND ', $conditions);
         $sql = "SELECT * FROM pay_qrlist WHERE $whereClause AND hook_type ='3' ORDER BY id DESC LIMIT $offset, $pagesize";
         $result = safeSqlQuery($sql, $params)['result'];
         
         if(!empty($id) && $my == 'edit'){
             $sql = "SELECT * FROM  pay_qrlist where id = '$id' limit 1";
             $row = executeSQLQuery($sql);
             $ckstatus = 'CooKie已失效，请勿强制开启二维码."';
            if(strlen($row['cookie'])>2){
                $ckstatus = 'CooKie状态正常';
            }
         }
          $token = json_encode(array("pid"=>$userrow['pid'],"key"=>$userrow['key']));
          $token= aes256auth($token,APPTOKENKEY);
          $tokenqr = $httphost.'|'.$token;
          
        include pluginstem.'APP_Qrlist.php';
    }
    public function add_appqr(){
        global $islogin_user,$date,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata    =  input("post");
        $type        =  $postdata['type'];
        $qr_url      =  $postdata['qr_url'];
        $beizhu      =  $postdata['beizhu'];
        if(empty($type) || empty($qr_url))exitjson(-1,'支付方式、二维码链接不可为空');
        Examine::usernum();
        Examine::uservip($type);
        $sql = "INSERT INTO `pay_qrlist` (`pid`,`type`, `qr_url`,`cookie`,`money`,`beizhu`,`status`,`hook_type`,`addtime`) VALUES (:pid,:type,:qr_url,:cookie,:money,:beizhu,:status,:hook_type,:date)";
        $params = [
           'pid'=>$user_pid,
           'type'=>$type,
           'qr_url'=>$qr_url,
           'cookie'=>'0',
           'money'=>'0.00',
           'beizhu'=>$beizhu,
           'status'=>'1',
           'hook_type'=>'3',
           'date'=>$date
        ];
        if (safeSqlQuery($sql, $params, 'insert'))exitjson(200,'添加成功！');
        exitjson(-1,'添加失败！');
    }
    public function auth(){
        if(PluginScanner::key($this->priKey,$this->info['pwd'],$this->info['path'],$this->info['auth']))exit("success");
    }
    public function Token_effect(){
        $token  = input("post")['token'];
        if(empty($token))exitjson(-1,'请输入token');
        $key =  PluginScanner::key($this->priKey,$this->info['pwd'],$this->info['path'],$this->info['auth']);
       
        if(auth::mactokenxy($token,pluginpwd,privateKey)){
            file_put_contents(authfile_path, $token);
            exitjson(200,'效验成功！');
        }
         exitjson(-1,'效验失败');
    }
    private function tokenkeyverify($token){
        $token1= aes256auth($token,APPTOKENKEY,"DECODE");
        
        if(!$token1)return false;
        $json = json_decode($token1,true);
        if(!$json)return false;
        $pid = $json['pid'];
        $key = $json['key'];
        
        $sql = "SELECT * FROM pay_user WHERE `pid`=:pid and `key`=:key limit 1";
        $paramsSelect = [
            'pid' => $pid,
            'key'=> $key
        ];
        $userrow = safeSqlQuery($sql, $paramsSelect)['result'][0];
        if($userrow){
            return array(
                   "pid"=>$pid,
                   "key"=>$key
               );
        }
        return false;
    }
    private function userrow($pid){
        $sql = "SELECT * FROM pay_user WHERE  `pid` = :pid LIMIT 1";
        $paramsSelect = [
            'pid' => $pid
        ];
        
        return safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
    }
}
?>